package com.itheima.reggie.pay.controller;


import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.itheima.reggie.pay.config.WeixinPayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author byZhao
 * @modify 2022-03-11 0:55
 * @description <p> </p>
 * <p> Talk is cheap . Show me the code! </p>
 */
@Controller
@RequestMapping("/pay")
public class PayController {


    @RequestMapping("/qrcode")
    public void generateQRCode(HttpServletResponse response) throws IOException, WriterException {
        Map<String, String> data = mockPay();
        String code_url = data.get("code_url");
        ServletOutputStream out = response.getOutputStream();
        Map<EncodeHintType, Object> config = new HashMap<>();
        config.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        config.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, 200, 200, config);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
        System.out.println("二维码生成完毕，已经输出到页面中。");

    }

    public Map<String, String> mockPay() {
        Map<String, String> resp = new HashMap<>();
        try {
            WXPayConfig config = new WeixinPayConfig();
            WXPay wxPay = new WXPay(config);
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "腾讯充值中心-QQ会员充值");
            data.put("out_trade_no", "2016090910595900004567");
            data.put("device_info", "");
            data.put("fee_type", "CNY");
            data.put("total_fee", "1");
            data.put("spbill_create_ip", "123.12.12.123");
            data.put("notify_url", "http://www.example.com/wxpay/notify");
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", "12");
            resp = wxPay.unifiedOrder(data);
            System.out.println(resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

}
